class Solution {
public:
    int atoi(const char *str) {
        int idx = 0, sign = 1, val = 0;
        // 1. 空字符串
        if (strlen(str) == 0) return 0;
        // 2. 忽略前置0
        while (str[idx] == ' ') ++idx;
        // 3. 记录符号
        if (str[idx] == '-') {sign = -1; ++idx;}
        if (str[idx] == '+') {++idx;}
        for (; idx < strlen(str); ++idx) {
            // 4. 处理非法值
            if (str[idx] > '9') break;
            // 5. 处理溢出
            if (val > INT32_MAX / 10 || (val == INT32_MAX / 10 && INT32_MAX % 10 < str[idx] - '0')) {
                return sign == 1 ? INT32_MAX : INT32_MIN;
            }
            val = val * 10 + str[idx] - '0';
        }
        return val * sign;
    }
};

class Solution2 {
public:
    int myAtoi(string s) {
        int n = s.length();
        if (n == 0) return 0;
        int result = 0, index = 0, sign = 1;
        while (s[index] == ' ') index++;
        if (s[index] == '+' || s[index] == '-') {
            sign = s[index] == '+' ? 1 : -1;
            index++;
        }
        while (s[index] >= '0' && s[index] <= '9') {
            if (result > INT_MAX / 10  || (result == INT_MAX / 10 && s[index] > '7'))
                return sign == 1 ? INT_MAX : INT_MIN;
            result = result * 10 + (s[index] - '0'); 
            index++;
        }
        return sign * result;
    }
};